from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from goods.models import Goods
from tools.send_mail_tool import send_email_code
from user.forms import UserRegisterForm, UserLoginForm
from user.models import UserProfile, Address, EmailVerifyCode

'''
    author: 赵向阳
    date  : 2019/11/06
'''


def index(request):
    resources = Goods.objects.all()
    # for re in resources:
    #     print('商品是：', re.name, re.type, re.desc, re.photo.url)
    return render(request, "index.html", {"resources": resources})


# 登录
@csrf_exempt
def user_login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        user_login_form = UserLoginForm(request.POST)
        if user_login_form.is_valid():
            username = user_login_form.cleaned_data['username']
            password = user_login_form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                if user.is_start == True:
                    login(request, user)
                    return redirect(reverse('user:index'))
                else:
                    return HttpResponse('去激活您的账号去吧')
            else:
                return render(request, 'login.html', {
                    'msg': '用户名或密码输入错误'
                })
        else:
            return render(request, 'login.html', {
                'msg': '请正常填写登录信息！！！'
            })
    return render(request, 'index.html')


def user_logout(request):
    logout(request)
    return render(request, 'index.html')


# 用户注册
@csrf_exempt
def user_register(request):
    if request.method == 'GET':
        # 启用验证码
        user_register_form = UserRegisterForm()
        return render(request, 'register.html', {
            'user_register_form': user_register_form
        })
    elif request.method == 'POST':
        user_register_form = UserRegisterForm(request.POST)
        if user_register_form.is_valid():
            username = user_register_form.cleaned_data['username']
            password = user_register_form.cleaned_data['password']
            c_password = user_register_form.cleaned_data['c_password']
            email = user_register_form.cleaned_data['email']

            if password == c_password:
                user_list = UserProfile.objects.filter(Q(username=username) | Q(email=email))
                if user_list:
                    return render(request, 'register.html', {
                        'msg': '用户已经存在(邮箱或者用户名已经使用)，请重新输入一个吧'
                    })

                else:
                    user = UserProfile()
                    user.username = username
                    user.set_password(password)
                    user.email = email
                    user.save()

                    send_email_code(email, 1)
                    return HttpResponse('快去激活账号')
                # return render(request, 'login.html', {
                #     'msg': '注册成功,请登录',
                # })
            else:
                return render(request, 'register.html', {
                    'msg': '两次密码不一致，请重新输入',
                })
    return render(request, 'register.html', {
        'user_register_form': user_register_form
    })


# 个人信息
@login_required(login_url='/user_login/')
def user_center_info(request):
    user = request.user
    info = {
        'name': user.username,
        'phone': user.phone,
    }
    return render(request, 'user_center_info.html', info)


@login_required(login_url='/user_login/')
def user_center_order(request):
    return render(request, 'user_center_order.html')


# 收货地址
@login_required(login_url='/user_login/')
def user_center_site(request):
    address = Address.objects.filter(a_user=request.user).last()
    if address:
        address_info = {
            'address': address.person_address,
            'person_name': address.person_name,
            'person_phone': address.person_phone
        }
    else:
        address_info = {
            'address': '',
            'person_name': '',
            'person_phone': ''
        }
    if request.method == 'GET':
        return render(request, 'user_center_site.html', address_info)
    elif request.method == 'POST':
        person_name = request.POST.get('person_name')
        person_address = request.POST.get('person_address')
        postcode = request.POST.get('postcode')
        person_phone = request.POST.get('person_phone')

        address_person = Address()
        address_person.person_name = person_name
        address_person.person_address = person_address
        address_person.postcode = postcode
        address_person.person_phone = person_phone
        address_person.a_user = request.user
        address_person.save()

        return redirect(reverse('user:user_center_site'))
    else:
        return render(request, 'index.html')


# 激活
def user_activate(request, code):
    print("卧槽")
    if code:
        email_ver_list = EmailVerifyCode.objects.filter(code=code)
        if email_ver_list:
            email_ver = email_ver_list[0]
            email = email_ver.email
            user_list = UserProfile.objects.filter(email=email)
            if user_list:
                user = user_list[0]
                user.is_start = True
                user.save()
                return redirect(reverse('user:user_login'))
            else:
                return HttpResponse('该用户不存在')
        else:
            return HttpResponse('验证码错误或者失效')
    return HttpResponse('赶紧去正确的邮箱激活吧')
